import { GridService } from '@service/grid.service';
import { BaseService } from '@service/base.service';
import { AbsFormUtil } from '@abstract/form';
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { TreeService } from '@service/tree.service';
import { NzFormatEmitEvent, NzTreeNode, NzTreeNodeOptions } from 'ng-zorro-antd/tree';
@Component({
	selector: 'app-base-area-edit',
	templateUrl: './base-area-edit.component.html',
	styleUrls: ['./base-area-edit.component.less']
})
export class BaseAreaEditComponent extends AbsFormUtil implements OnInit {
	@ViewChild('treeNode') treeNode;
	@Input() id: string;
	areaAddrOptions = [];
	areaList = [];
	householdList = [];
	gongTree = [];
	gongList = [];
	constructor(
		private nzMessageService: NzMessageService,
		private fb: FormBuilder,
		private nzModalRef: NzModalRef,
		private baseService: BaseService,
		private gridService: GridService,
		private treeService: TreeService
	) {
		super();
	}

	ngOnInit() {
		this.buildForm();
		this.getCommunityTree();
	}

	private async getGridAreaInfo() {
		const result = await this.baseService.getGridAreaInfo(this.id);
		const gridAreaInfo = result.data;
		const areaItem = this.areaList.find(itm => itm.id === String(gridAreaInfo.ownerCommunity));
		gridAreaInfo.ownerCommunity = areaItem ? this.getAreaId(areaItem, [String(gridAreaInfo.ownerCommunity)]) : '';
		gridAreaInfo.houseHoldSave = gridAreaInfo.houseHolds ? gridAreaInfo.houseHolds.map(Number) : []
		this.validateForm.patchValue(gridAreaInfo);
		this.getInfoForDong();
	}
	// private async getHouseholdSelectByAreae(areaId: string) {
	// 	const result = await this.gridService.getHouseholdSelectByAreae(areaId);
	// 	this.householdList.push({
	// 		id: areaId,
	// 		children: result.data
	// 	});
	// }

	// private setTree() {
	// 	this.gongList.forEach(gong => {
	// 		const household = this.householdList.find(it => it.id == gong.id);
	// 		if (household) {
	// 			gong.children = household.children.map(itm => {
	// 				return {
	// 					key: itm.id.toString(),
	// 					title: gong.title + '-' + itm.address,
	// 					isLeaf: true,
	// 					value: itm.id
	// 				}
	// 			})
	// 		}
	// 	});
	// }
	private async getDongTree(areaId: string) {
		const result = await this.gridService.getDongTree(areaId);
		this.gongList = result.data.filter(Boolean);
		let parentId = null;
		this.gongList.forEach(item => {
			item.title = item.areaFullName;
			item.value = Number(item.id);
			item.key = Number(item.id);
			item.isLeaf = !this.gongList.some(itm => itm.parentId == item.id);
			if (this.gongList.some(itm => itm.parentId == item.id) && !parentId) {
				parentId = item.parentId;
			}
		});
		// this.setTree();
		this.gongTree = this.treeService.convertListToTree(this.gongList, parentId);
	}
	getAreaId(area, result: string[]) {
		const areaItem = this.areaList.find(itm => itm.id === String(area.parentId));
		if (areaItem) {
			result.unshift(String(areaItem.id));
			if (areaItem.parentId) {
				return this.getAreaId(areaItem, result);
			}
			return result;
		}
	}
	private async getCommunityTree() {
		const result = await this.baseService.getCommunityTree();
		this.areaList = result.data;
		this.areaList.forEach(it => {
			it.label = it.areaFullName;
			it.value = it.id;
			it.isLeaf = !this.areaList.some(itm => itm.parentId == it.id);
		});
		if (this.id) {
			this.getGridAreaInfo();
		}
		this.areaAddrOptions = this.treeService.convertListToTree(this.areaList, 0);
	}

	private async getInfoForDong() {
		const result = await this.gridService.getInfoForDong(this.id);
		// result.data.forEach(id => {
		// 	this.getHouseholdSelectByAreae(id);
		// });
		const houseHoldSave = (result.data || []).filter(Boolean).map(Number);
		// if (houseHoldSave.length) {
			this.validateForm.controls.houseHoldSave.setValue(houseHoldSave);
		// }
		this.validateForm.controls.houseHolds.setValue(houseHoldSave);

	}
	buildForm() {
		this.validateForm = this.fb.group({
			gridAreaName: ['', Validators.required],
			ownerCommunity: [[], Validators.required],
			houseHoldSave: [[]],
			gridDescription: ['', Validators.required],
			houseHolds: [[]]
		});
	}

	ownerCommunityChange(val) {
		const areaId = val[val.length - 1];
		// this.getHouseholdSelectByAreae(areaId);
		this.getDongTree(areaId);
		this.getFormControl('houseHoldSave').setValue([]);
	}

	onSubmit() {
		this.markAsDirty();
		if (this.validateForm.invalid) {
			return;
		}
		const formRes = this.validateForm.value;
		if (formRes.houseHoldSave) {
			const houseHoldSave = [];
			formRes.houseHoldSave.forEach(id => {
				const houseHold = this.gongList.find(it => it.value === id);
				if (!houseHold?.isLeaf){
					const filterHouseHold = this.gongList.filter(it => it.parentId === id);
					houseHoldSave.push(...filterHouseHold.map(itm => itm.id));
				} else {
					houseHoldSave.push(id)
				}
			});
			formRes.houseHoldSave = houseHoldSave;
		}
		return { ...this.validateForm.value };
		return ;
	}
	destroyModal() {
		this.nzModalRef.destroy();
	}

	onChange(val) {
		// console.log(val);
		// console.log(this.treeNode.getCheckedNodeList());
	}

	// onExpandChange(e: NzFormatEmitEvent): void {
	// 	const node = e.node;
	// 	if (node && node.getChildren().length === 0 && node.isExpanded) {
	// 		this.loadNode(node).then(data => {
	// 			node.addChildren(data);
	// 			// node.isDisableCheckbox = false;
	// 		});
	// 	}
	// }


	// loadNode(node): Promise<NzTreeNodeOptions[]> {
	// 	return new Promise(async (resolve) => {
	// 		const result = await this.gridService.getHouseholdSelectByAreae(node.origin.id);
	// 		const householdList = result.data;
	// 		householdList.forEach(it => {
	// 			it.key = it.id.toString();
	// 			it.title = node.origin.title + '-' + it.address;
	// 			it.isLeaf = true;
	// 		});
	// 		resolve(householdList)
	// 	});
	// }
	nzDisplayWith = (node: NzTreeNode) => {
		if (node?.parentNode?.origin) {
			return node.parentNode.origin.title + '-' + node.title;
		}
		return node.title;
	}

}
